﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Xml.Serialization;

namespace Metozis.SimpleXMLSerialization.Products
{
    //Serializing product class that Contains a Field Returning a Complex Object (ex. a class instance)
    //If a property or field returns a complex object (product.Category), the XmlSerializer converts it to an element nested within the XML document.

    public class ProductsRepository : IRepository
    {
        private string _path;

        public ProductsRepository(string path)
        {
            _path = path;
        }

        public void ReadXml()
        {
            var serializer = new XmlSerializer(typeof (List<Product>));

            var reader = new FileStream("products.xml", FileMode.Open, FileAccess.Read, FileShare.Read);

            var products = (IEnumerable<Product>) serializer.Deserialize(reader);

            reader.Close();
            Console.WriteLine("   Preview of XML file created   ");
            Console.WriteLine("{0,15} {1,15} {2,15}", "Name", "Category", "Serial Number");
            foreach (Product product in products)
            {
                Console.WriteLine("{0,15} {1,15} {2,15}", product.Name, product.Category.Name, product.SerialNumber);
            }
            Console.WriteLine("");
        }

        public void WriteXml()
        {
            var serializer = new XmlSerializer(typeof (List<Product>));

            var category1 = new Category {Name = "Laptop"};
            var category2 = new Category {Name = "HDD"};
            var products = new List<Product>();
            products.Add(new Product {Name = "HP", Category = category1, SerialNumber = "0123"});
            products.Add(new Product {Name = "Dell", Category = category1, SerialNumber = "1123"});
            products.Add(new Product {Name = "Fujitsu", Category = category1, SerialNumber = "2123"});
            products.Add(new Product {Name = "WD", Category = category2, SerialNumber = "0120"});
            products.Add(new Product {Name = "Hitachi", Category = category2, SerialNumber = "1120"});
            products.Add(new Product {Name = "Toshiba", Category = category2, SerialNumber = "2120"});
            products.Add(new Product { Category = category2, SerialNumber = "2230" });
            
            /*when [XmlElement(IsNullable = true)] xsi:nil attribute is generated for the field Name.
             If false then Name field is not serialized at all.*/
            //Check it out on http://msdn.microsoft.com/en-us/library/system.xml.serialization.xmlelementattribute.isnullable.aspx?cs-save-lang=1&cs-lang=csharp#code-snippet-1

            TextWriter writer = new StreamWriter("products.xml");
            serializer.Serialize(writer, products);

            writer.Close();
        }
    }
}